package com.handong.handserialprogram.thread;

import android.os.Process;

import com.handong.handserialprogram.model.status.EmergencyResponse;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SPUtil;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * Created by userKey on 2017/4/12.
 */

public class EmergencyRunnable implements Runnable {

    private static final String TAG = EmergencyRunnable.class.getSimpleName();

    private NioSocketConnector mConnector;
    private IoSession mSession;

    private byte[] mUploadBuff;
    private int mCount = 0;
    private int mFailCount = 0;

    private boolean mIsConnectedSuccess = false;

    public EmergencyRunnable(byte[] uploadBuff) {
        this.mUploadBuff = uploadBuff;
    }

    @Override
    public void run() {
        //设置为后台线程 避免与main线程争夺资源。
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        while (true) {
            try {
                if (mCount == 3) {
                    postResult(new EmergencyResponse(200, "success"));
                    closeMinaSocket();
                    out(Thread.currentThread().getId() + " has destroy.");
                    break;
                }

                if (mFailCount == -3) {
                    postResult(new EmergencyResponse(404, "error"));
                    closeMinaSocket();
                    out(Thread.currentThread().getId() + " has destroy.");
                    break;
                }
                uploadWarningInformation();
            } catch (Exception e) {
                e.printStackTrace();
                mFailCount--;
            }
        }
    }

    /**
     * 上传警告信息。
     */
    private void uploadWarningInformation() throws Exception {

        initConnection();

        if (mSession != null && mSession.isConnected()) {
            if (!mIsConnectedSuccess) {
                Thread.sleep(1500);
                mIsConnectedSuccess = true;
            }
            //String data = Tools.byteToHexString(mUploadBuff);
            //JLog.d(TAG, "Upload Data:"+data);
            IoBuffer buffer = IoBuffer.wrap(mUploadBuff);
            mSession.write(buffer);
            out("socket uploadWarningInformation success.");
            mCount++;

            if (mCount == 3 || mFailCount == -3) {
                return;
            }
            Thread.sleep(500);
        }
    }

    private void initConnection() throws Exception {
        if (mConnector == null) {
            out("客户端开始链接");
            mConnector = new NioSocketConnector();
            mConnector.setConnectTimeoutMillis(3000);
            mConnector.getFilterChain().addLast(
                    "codec",
                    new ProtocolCodecFilter(new TextLineCodecFactory(Charset
                            .forName("UTF-8"),
                            LineDelimiter.WINDOWS.getValue(),
                            LineDelimiter.WINDOWS.getValue())));
            mConnector.setHandler(new MinaClientHandler());
            String ip = SPUtil.getStringValue(SPUtil.SERVER_IP);
            int port = SPUtil.getIntValue(SPUtil.UPLOAD_PORT);
            //String ip = "10.1.200.95";
            //int port = 9503;
            mConnector.setDefaultRemoteAddress(new InetSocketAddress(
                    ip, port));

            mConnector.addListener(new IoListener() {

                @Override
                public void sessionDestroyed(IoSession arg0) throws Exception {
                    super.sessionDestroyed(arg0);
                    mSession = null;
                    mIsConnectedSuccess = false;
                }
            });
        }

        if (mSession == null) {
            ConnectFuture future = mConnector.connect();
            future.awaitUninterruptibly();// 等待连接创建完成
            mSession = future.getSession();
        }
    }

    private void postResult(EmergencyResponse result) {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        EventBusUtil.post(result);
    }

    public void closeMinaSocket() {

        if (mSession != null) {
            mSession.closeNow();
            //mSession.getCloseFuture().awaitUninterruptibly(1000);
            mSession = null;
        }

        if (mConnector != null) {
            mConnector.dispose();
            mConnector = null;
        }
    }

    public static void out(String s) {
        JLog.d(TAG, s);
    }
}
